<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深度调试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 25px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            margin-top: 0;
        }
        h2 {
            color: #555;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        h3 {
            color: #666;
        }
        button {
            padding: 10px 20px;
            margin: 10px 10px 10px 0;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }
        .btn-primary:hover {
            background-color: #45a049;
        }
        .btn-secondary {
            background-color: #2196F3;
            color: white;
        }
        .btn-secondary:hover {
            background-color: #0b7dda;
        }
        .btn-danger {
            background-color: #f44336;
            color: white;
        }
        .btn-danger:hover {
            background-color: #d32f2f;
        }
        pre {
            background-color: #f1f1f1;
            padding: 15px;
            border-radius: 4px;
            overflow-x: auto;
            max-height: 400px;
            font-family: 'Courier New', Courier, monospace;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .log-entry {
            margin-bottom: 5px;
            border-left: 3px solid #ddd;
            padding-left: 10px;
        }
        .log-info {
            color: #2196F3;
        }
        .log-success {
            color: #4CAF50;
        }
        .log-error {
            color: #f44336;
        }
        .log-warning {
            color: #ff9800;
        }
        .info-box {
            background-color: #e3f2fd;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            border-left: 4px solid #2196F3;
        }
        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        @media (max-width: 768px) {
            .grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>深度调试工具</h1>
        <div class="info-box">
            <h3>问题分析</h3>
            <p>当前获取验证码时出现<strong>HTTP 404错误</strong>。此页面将帮助诊断问题根源。</p>
            <p>后端服务运行在端口: <strong>8000</strong></p>
            <p>前端服务器运行在端口: <strong>8000</strong></p>
            <p>验证码API路径: <strong>/api/auth/captcha</strong></p>
        </div>
    </div>

    <div class="container">
        <h2>连接测试</h2>
        <div class="grid">
            <div>
                <h3>直接连接后端服务</h3>
                <p>绕过前端服务器，直接向后端服务发送请求。</p>
                <button id="testDirectBackend" class="btn-primary">测试直接连接</button>
                <pre id="directBackendLog"></pre>
            </div>
            <div>
                <h3>通过前端服务器连接</h3>
                <p>模拟正常应用流程，通过前端服务器转发请求。</p>
                <button id="testThroughFrontend" class="btn-secondary">测试转发连接</button>
                <pre id="frontendLog"></pre>
            </div>
        </div>
    </div>

    <div class="container">
        <h2>网络状态检查</h2>
        <button id="checkNetworkStatus" class="btn-warning">检查网络状态</button>
        <pre id="networkStatusLog"></pre>
    </div>

    <div class="container">
        <h2>验证码显示测试</h2>
        <button id="displayCaptcha" class="btn-success">尝试显示验证码</button>
        <div style="margin-top: 20px;">
            <img id="captchaImage" style="max-width: 100%; display: none; border: 1px solid #ddd; padding: 5px;" alt="验证码" />
        </div>
        <pre id="captchaLog"></pre>
    </div>

    <script>
        // 日志功能
        function log(containerId, type, message) {
            const container = document.getElementById(containerId);
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `<div class="log-entry log-${type}">[${timestamp}] [${type.toUpperCase()}] ${message}</div>`;
            container.innerHTML += logEntry;
            container.scrollTop = container.scrollHeight;
        }

        function clearLog(containerId) {
            document.getElementById(containerId).innerHTML = '';
        }

        // 直接测试后端服务连接
        document.getElementById('testDirectBackend').addEventListener('click', async function() {
            clearLog('directBackendLog');
            log('directBackendLog', 'info', '开始测试直接连接后端服务...');
            log('directBackendLog', 'info', '后端服务URL: http://localhost:8000/api/auth/captcha');
            
            try {
                const timestamp = new Date().getTime();
                const url = `http://localhost:8000/api/auth/captcha?t=${timestamp}`;
                
                log('directBackendLog', 'info', `发送请求到: ${url}`);
                
                const startTime = performance.now();
                const response = await fetch(url, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    },
                    mode: 'cors'
                });
                const endTime = performance.now();
                
                log('directBackendLog', 'info', `请求完成，耗时: ${Math.round(endTime - startTime)}ms`);
                log('directBackendLog', 'info', `状态码: ${response.status}, 状态: ${response.statusText}`);
                
                // 记录响应头
                log('directBackendLog', 'info', '\n响应头信息:');
                const headers = {};
                response.headers.forEach((value, name) => {
                    headers[name] = value;
                    log('directBackendLog', 'info', `  ${name}: ${value}`);
                });
                
                // 检查CORS相关头
                if (headers['access-control-allow-origin']) {
                    log('directBackendLog', 'success', `CORS允许的源: ${headers['access-control-allow-origin']}`);
                } else {
                    log('directBackendLog', 'warning', '未检测到CORS允许源头');
                }
                
                if (response.ok) {
                    try {
                        const data = await response.json();
                        log('directBackendLog', 'success', '\n成功获取响应数据:');
                        log('directBackendLog', 'success', JSON.stringify(data, null, 2));
                    } catch (jsonError) {
                        log('directBackendLog', 'error', `解析JSON失败: ${jsonError.message}`);
                    }
                } else {
                    log('directBackendLog', 'error', `请求失败，状态码: ${response.status}`);
                }
            } catch (error) {
                log('directBackendLog', 'error', `请求异常: ${error.message}`);
                log('directBackendLog', 'error', `错误类型: ${error.constructor.name}`);
                
                if (error.message.includes('Failed to fetch')) {
                    log('directBackendLog', 'error', '\n可能的原因:');
                    log('directBackendLog', 'error', '1. 后端服务未运行');
                    log('directBackendLog', 'error', '2. 防火墙阻止了连接');
                    log('directBackendLog', 'error', '3. CORS配置不正确');
                    log('directBackendLog', 'error', '4. 后端服务崩溃');
                }
            }
        });

        // 测试通过前端服务器连接
        document.getElementById('testThroughFrontend').addEventListener('click', async function() {
            clearLog('frontendLog');
            log('frontendLog', 'info', '开始测试通过前端服务器连接...');
            log('frontendLog', 'info', '前端服务器URL: /api/auth/captcha');
            
            try {
                const timestamp = new Date().getTime();
                const url = `/api/auth/captcha?t=${timestamp}`;
                
                log('frontendLog', 'info', `发送请求到: ${url}`);
                
                const startTime = performance.now();
                const response = await fetch(url, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                const endTime = performance.now();
                
                log('frontendLog', 'info', `请求完成，耗时: ${Math.round(endTime - startTime)}ms`);
                log('frontendLog', 'info', `状态码: ${response.status}, 状态: ${response.statusText}`);
                
                // 记录响应头
                log('frontendLog', 'info', '\n响应头信息:');
                response.headers.forEach((value, name) => {
                    log('frontendLog', 'info', `  ${name}: ${value}`);
                });
                
                if (response.ok) {
                    try {
                        const data = await response.json();
                        log('frontendLog', 'success', '\n成功获取响应数据:');
                        log('frontendLog', 'success', JSON.stringify(data, null, 2));
                    } catch (jsonError) {
                        log('frontendLog', 'error', `解析JSON失败: ${jsonError.message}`);
                    }
                } else {
                    log('frontendLog', 'error', `请求失败，状态码: ${response.status}`);
                    
                    if (response.status === 404) {
                        log('frontendLog', 'error', '\n可能的原因:');
                        log('frontendLog', 'error', '1. 前端服务器未配置代理');
                        log('frontendLog', 'error', '2. API路径错误');
                        log('frontendLog', 'error', '3. 后端服务未运行');
                    }
                }
            } catch (error) {
                log('frontendLog', 'error', `请求异常: ${error.message}`);
            }
        });

        // 检查网络状态
        document.getElementById('checkNetworkStatus').addEventListener('click', function() {
            clearLog('networkStatusLog');
            log('networkStatusLog', 'info', '开始检查网络状态...');
            
            // 显示当前页面信息
            log('networkStatusLog', 'info', `当前页面URL: ${window.location.href}`);
            log('networkStatusLog', 'info', `浏览器: ${navigator.userAgent}`);
            log('networkStatusLog', 'info', `域名: ${window.location.hostname}`);
            log('networkStatusLog', 'info', `端口: ${window.location.port}`);
            
            // 检查连接类型
            if ('connection' in navigator) {
                const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
                log('networkStatusLog', 'info', `\n网络连接类型: ${connection.type}`);
                log('networkStatusLog', 'info', `有效带宽: ${connection.downlink} Mbps`);
            }
            
            // 尝试ping后端服务
            log('networkStatusLog', 'info', '\n尝试ping后端服务...');
            pingBackendService();
        });

        // 简单的后端服务ping功能
        function pingBackendService() {
            const startTime = performance.now();
            const img = new Image();
            
            img.onload = function() {
                const endTime = performance.now();
                log('networkStatusLog', 'success', `后端服务可访问，延迟: ${Math.round(endTime - startTime)}ms`);
            };
            
            img.onerror = function() {
                const endTime = performance.now();
                log('networkStatusLog', 'warning', `后端服务可能不可访问或图片不存在，响应时间: ${Math.round(endTime - startTime)}ms`);
            };
            
            img.src = `http://localhost:8000/favicon.ico?${new Date().getTime()}`;
        }

        // 尝试显示验证码
        document.getElementById('displayCaptcha').addEventListener('click', async function() {
            clearLog('captchaLog');
            const captchaImage = document.getElementById('captchaImage');
            captchaImage.style.display = 'none';
            
            log('captchaLog', 'info', '尝试获取并显示验证码...');
            
            try {
                const timestamp = new Date().getTime();
                // 直接连接后端服务获取验证码
                const url = `http://localhost:8000/api/auth/captcha?t=${timestamp}`;
                
                log('captchaLog', 'info', `发送请求到: ${url}`);
                
                const response = await fetch(url, {
                    method: 'GET',
                    credentials: 'include',
                    headers: {
                        'Accept': 'application/json'
                    },
                    mode: 'cors'
                });
                
                if (response.ok) {
                    const data = await response.json();
                    log('captchaLog', 'success', '成功获取验证码数据');
                    
                    if (data && data.captchaImage) {
                        captchaImage.src = data.captchaImage;
                        captchaImage.style.display = 'block';
                        log('captchaLog', 'success', '验证码图片显示成功');
                        log('captchaLog', 'info', `验证码Token: ${data.captchaToken || '未提供'}`);
                    } else {
                        log('captchaLog', 'error', '验证码数据格式不正确，缺少必要字段');
                    }
                } else {
                    log('captchaLog', 'error', `获取验证码失败，状态码: ${response.status}`);
                }
            } catch (error) {
                log('captchaLog', 'error', `获取验证码异常: ${error.message}`);
            }
        });
    </script>
</body>
</html>